package servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import dao.CountryDAO;
import domain.Country;

/**
 * Servlet implementation class CountryServlet
 */
@WebServlet("/country")
public class CountryServlet extends HttpServlet {
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		resp.setContentType("text/html;charset=utf-8");
		PrintWriter pw = resp.getWriter();
		
		// 1. 获取提交的参数
		String code = req.getParameter("code");
		
		// 2. 调用模型
		CountryDAO dao = new CountryDAO();
		
		String jsonStr = null;
		if(code!=null)
		{
			try {
				Country c = dao.findByCode(code);
				
				jsonStr = JSONObject.toJSONString(c);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
		else
		{
			try {
				List<Country> list = dao.findAll();
				
				jsonStr = JSONArray.toJSONString(list);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
		pw.print(jsonStr);
		
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doGet(req, resp);
	}
}


// 练习:
// 实现城市的接口
// city				显示所有的json数组
// city?id=1		显示这个城市的json信息